// ActionScript file
import flash.events.Event;

import jpa.domain.Storage;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.mxml.RemoteObject;

import web.storage.StorageForm;
			
			[Bindable]
			private var contacts:ArrayCollection;
			
			private var ro:RemoteObject;

			private function resultHandler(event:ResultEvent):void
			{
				contacts = event.result as ArrayCollection
			}

			private function faultHandler(event:FaultEvent):void
			{
				Alert.show(event.fault.faultDetail);
			}

			public function openContact(storage:Storage):void
			{
				var children:Array = tn.getChildren();
				for (var i:int = 0; i<children.length; i++)
				{
					if (StorageForm(children[i]).storage.id == storage.id)
					{
						tn.selectedChild = children[i];
						return;
					}
				}
				
				var form:StorageForm = new StorageForm();
				form.addEventListener(StorageEvent.CREATED, contactCreatedHandler);
				form.addEventListener(StorageEvent.UPDATED, contactUpdatedHandler);
				form.addEventListener(StorageEvent.DELETED, contactDeletedHandler);
				tn.addChild(form);
				form.storage = storage;
				tn.selectedChild = form;
			}
			
			public function getStorageById(evt:Event):void{
				var id:uint=contacts[evt.currentTarget.selectedIndex]['id'];
				ro=Global.getRemoteObject("storageController",true,getStorageByIdHandler);
				ro.getStorageById(id);
			}
			
			
			private function getStorageByIdHandler(event:ResultEvent):void
			{
				var storage:Storage = event.result as Storage;
				
				openContact(storage);
			}

			private function search():void
			{
				
				ro=Global.getRemoteObject("storageController",true,resultHandler);
				ro.getMyStorageList();
			}

			private function contactCreatedHandler(event:StorageEvent):void
			{
				search();				
			}

			private function contactUpdatedHandler(event:StorageEvent):void
			{
				search();				
			}

			private function contactDeletedHandler(event:StorageEvent):void
			{
				tn.removeChild(event.target as StorageForm);
				search();				
			}